#include "Mcat/snake.h"

static int _rand=26;
static int score=0;

int rand(){
	_rand=((_rand)*(_rand)*56+2)%1000;
	return _rand;
}

int snakeRun()
{
	int n;
	Initial();
	Show();
	return 0;
}



void Initial()  //Init
{
	int i, j;
	int hx, hy;
	memset(GameMap, '.', sizeof(GameMap));  // init the map of the game
	
	hx = rand() % H;    
	hy = rand() % L;
	GameMap[hx][hy] = Shead;
	Snake[0].x = hx;  Snake[0].y = hy;
	Snake[0].now = -1;
	Create_Food();   //create the first food
	for (i = 0; i < H; i++)   //print
	{
		for (j = 0; j < L; j++)
			printf("%c", GameMap[i][j]);
		printf("\n");
	}

	printf("Game Begin\n");

	getch();   
	Button();  
}
void Create_Food()  
{
	int fx, fy;
	while (1)
	{
		fx = rand() % H;
		fy = rand() % L;

		if (GameMap[fx][fy] == '.')  
		{
			GameMap[fx][fy] = Sfood;
			break;
		}
	}
}
void Show() 
{
	int i, j;
	while (1)
	{
		//_sleep(500); 
		Button();   
		Move();
		if (over)  
		{
			printf("\nGame Over\n");
			printf("     >_<   \n");
			
			break;
		}
		console_clear();
		for (i = 0; i < H; i++)
		{
			for (j = 0; j < L; j++)
				printf("%c", GameMap[i][j]);
			printf("\n");
		}
		printf("\n Score : %d\n", score);
	}
}
void Button() 
{
		key=getchInStep(2000000);
		printf("%d\n", key);
		switch (key)
		{   //up
		case 75:  Snake[0].now = 0;
			break;
			//right  
		case 77:  Snake[0].now = 1;
			break;
			//left
		case 72:  Snake[0].now = 2;
			break;
			//down  
		case 80:  Snake[0].now = 3;
			break;
		}
}
void Move()   
{
	int i, x, y;
	int t = sum;  
	x = Snake[0].x;  y = Snake[0].y;  GameMap[x][y] = '.';
	Snake[0].x = Snake[0].x + dx[Snake[0].now];
	Snake[0].y = Snake[0].y + dy[Snake[0].now];
	Check_Border();
	Check_Head(x, y);  
	if (sum == t)  
	for (i = 1; i < sum; i++) 
	{
		if (i == 1)   
			GameMap[Snake[i].x][Snake[i].y] = '.';
		if (i == sum - 1)  
		{
			Snake[i].x = x;
			Snake[i].y = y;
			Snake[i].now = Snake[0].now;
		}
		else   
		{
			Snake[i].x = Snake[i + 1].x;
			Snake[i].y = Snake[i + 1].y;
			Snake[i].now = Snake[i + 1].now;
		}
		GameMap[Snake[i].x][Snake[i].y] = '#'; 
	}
}
void Check_Border()  
{
	if (Snake[0].x < 0 || Snake[0].x >= H
		|| Snake[0].y < 0 || Snake[0].y >= L)
		over = 1;
}
void Check_Head(int x, int y)  
{

	if (GameMap[Snake[0].x][Snake[0].y] == '.') 
		GameMap[Snake[0].x][Snake[0].y] = '@';
	else
	if (GameMap[Snake[0].x][Snake[0].y] == '*')
	{
		GameMap[Snake[0].x][Snake[0].y] = '@';
		Snake[sum].x = x; 
		Snake[sum].y = y;
		Snake[sum].now = Snake[0].now;
		GameMap[Snake[sum].x][Snake[sum].y] = '#';
		sum++;
		score++;
		Create_Food();  
	}
	else
		over = 1;
}